<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item prop="menuName">
        <template #label>
          <span class="font-bold">菜单名称</span>
        </template>
        <el-input
            v-model="queryParams.menuName"
            placeholder="请输入菜单名称"
            @keyup.enter="handleQuery"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <template #label>
          <span class="font-bold">菜单状态</span>
        </template>
        <el-select v-model="queryParams.status" placeholder="菜单状态" clearable>
          <el-option label="启用" :value="false"/>
          <el-option label="停用" :value="true"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery" @keyup.enter="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div >
    <el-button type="primary" plain @click="handleAdd"><el-icon><Plus /></el-icon> 新增</el-button>
      <el-button type="info" plain @click="handleExpandAll"><el-icon class="ml-5"><Sort /></el-icon> 展开/折叠</el-button>
    </div>

  <el-scrollbar>
    <el-table
        :data="tableData"
        v-if="refreshTable"
        fit
        v-loading="loading"
        row-key="menuId"
        table-layout="auto"
        style="width: 100%; margin-top: 15px;"
        :header-cell-style="{ background:'#eee'}"
        :default-expand-all="isExpandAll"
    >
      <el-table-column prop="menuName" label="菜单名称" min-width="200"/>
      <el-table-column prop="icon" label="图标" width="80" align="center">
        <template #default="scope">
          <component :is="scope.row.icon" v-if="scope.row.icon" style="width: 16px; height: 16px"></component>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" align="center" />
      <el-table-column prop="perms" label="权限标识" />
      <el-table-column prop="path" label="路由地址"/>
      <el-table-column prop="component" label="组件路径"/>
      <el-table-column prop="updateTime" label="更新时间" align="center"/>
      <el-table-column prop="status" label="是否隐藏" align="center">
        <template #default="scope">
          <el-tag v-if="!scope.row.visible" >显示</el-tag>
          <el-tag v-if="scope.row.visible" type="info">隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="菜单状态" align="center">
        <template #default="scope">
          <el-tag v-if="!scope.row.status" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status" type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template #default="scope">
          <el-button
              size="small"
              text
              type="primary"
              :icon="Edit"
              @click="handleEdit(scope.row.menuId)"
          >修改</el-button>
          <el-button
              size="small"
              text
              type="danger"
              :icon="Delete"
              @click="handleDelete(scope.row.menuId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-scrollbar>

  <!--  新增菜单弹出框-->
  <el-dialog
      v-model="centerDialogVisible"
      :title="dialogTitle"
      width="40%"
      top="10vh"
      @close="onCloseDialog"
      @open="onOpenDialog"
  >
    <el-form :model="menu" ref="menuForm" label-position="right"  label-width="100px" :rules="rules" size="large">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="parentId">
            <template #label>
              <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                <el-icon class="label-icon-center"><QuestionFilled /></el-icon>
              </el-tooltip>
              <span class="font-bold">上级菜单</span>
            </template>
            <el-tree-select v-model="menu.parentId" :data="menuOptions" check-strictly style="width: 100%" />
            <!--            <el-input v-model="menu.menuName" placeholder="请输入上级菜单" clearable />-->
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="menuType">
            <template #label>
              <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                <el-icon class="label-icon-center"><QuestionFilled /></el-icon>
              </el-tooltip>
              <span class="font-bold">菜单类型</span>
            </template>
            <el-radio-group v-model="menu.menuType">
              <el-radio label="M">目录</el-radio>
              <el-radio label="C">菜单</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="menuName">
            <template #label>
              <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                <el-icon class="label-icon-center"><QuestionFilled /></el-icon>
              </el-tooltip>
              <span class="font-bold">菜单名称</span>
            </template>
            <el-input v-model="menu.menuName" placeholder="请输入菜单名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="icon">
            <template #label>
              <span class="font-bold">菜单图标</span>
            </template>
            <el-icon class="label-icon-center" size="16">
              <component :is="menu.icon"></component>
            </el-icon>
            <el-autocomplete
                v-model="menu.icon"
                :fetch-suggestions="querySearch"
                popper-class="my-autocomplete"
                placeholder="请输入图标名称"
                style="width: calc(100% - 20px);"
            >
              <template #default="{ item }">
                <el-icon class="label-icon-center">
                  <component :is="item.value"></component>
                </el-icon>
                <span class="value">{{ item.value }}</span>
              </template>
            </el-autocomplete>
            <!--            <el-input :prefix-icon="menu.icon" v-model="menu.icon" placeholder="请输入菜单图标" clearable />-->
            <!--            <el-popover-->
            <!--                placement="bottom-start"-->
            <!--                width="460"-->
            <!--                trigger="click"-->
            <!--            >-->
            <!--              <template #reference>-->
            <!--                <el-input v-model="menu.icon" placeholder="点击选择图标" :prefix-icon="menu.icon == '' ? menu.icon : 'Search'">-->
            <!--                </el-input>-->
            <!--              </template>-->
            <!--&lt;!&ndash;              <el-icon class="label-icon-center"><component :is="menu.icon"></component></el-icon>&ndash;&gt;-->

            <!--            </el-popover>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="orderNum">
            <template #label>
              <span class="font-bold">显示排序</span>
            </template>
            <el-input-number v-model="menu.orderNum" controls-position="right" :min="0" style="width: 100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="path">
            <template #label>
              <span class="font-bold">路由地址</span>
            </template>
            <el-input v-model="menu.path" placeholder="组件路径" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="menu.menuType != 'M'">
          <el-form-item prop="perms">
            <template #label>
              <span class="font-bold">权限标识</span>
            </template>
            <el-input v-model="menu.perms" placeholder="请输入权限标识" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="menu.menuType == 'C'">
          <el-form-item prop="component">
            <template #label>
              <span class="font-bold">组件路径</span>
            </template>
            <el-input v-model="menu.component" placeholder="请输入组件路径" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="visible">
            <template #label>
              <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                <el-icon class="label-icon-center"><QuestionFilled /></el-icon>
              </el-tooltip>
              <span class="font-bold">是否隐藏</span>
            </template>
            <el-radio-group v-model="menu.visible">
              <el-radio :label="false">显示</el-radio>
              <el-radio :label="true">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="status">
            <template #label>
              <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                <el-icon class="label-icon-center"><QuestionFilled /></el-icon>
              </el-tooltip>
              <span class="font-bold">菜单状态</span>
            </template>
            <el-radio-group v-model="menu.status">
              <el-radio :label="false">启用</el-radio>
              <el-radio :label="true">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

      </el-row>

    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSubmit">确定</el-button>
      <el-button type="info" @click="onCancel" style="margin-right: 10%">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref, nextTick, defineEmits} from "vue";
import {getList, getMenuTreeSelect, getMenu, addMenu, updateMenu, getIcons, deleteMenu} from "../../../api/menu.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Edit, Delete, Search, Refresh, Sort} from "@element-plus/icons-vue";

const emit = defineEmits(['hidden','show']) //未用到，加上解决警告，问题在哪不知道
  const tableData = ref([])
  const state = ref('')
  const select = ref('menuName')
  const centerDialogVisible = ref(false)
  const loading = ref(true)
  const menuForm = ref(null)
  const menu = reactive(defaultValue())
  const restaurants = ref([])
  const menuOptions = ref([])
  const dialogTitle = ref('新增菜单')
  const isExpandAll = ref(false)
  const refreshTable = ref(true)
  const queryParams = reactive({
    menuName: null,
    status: null,
  })

  function defaultValue(){
    return {
      menuId: null,
      menuName: null,
      orderNum: null,
      parentId: 0,
      path: null,
      component: null,
      visible: false,
      status: false,
      perms: null,
      icon: null,
      children: [],
      menuType: 'M'
    }
  }

const rules = {
  menuName: [
    {required: true, message: '菜单名称不能为空', trigger: 'blur'},
    // {pattern: /^[a-zA-Z0-9]{4,20}$/, message: '用户名长度为4 - 20位'}
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入正确的邮箱'}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,18}$/, message: '密码格式错误，必须包含大小写字母和数字，且长度在4-18位'}
  ],
  realName: [
    {required: true, message: '真实姓名不能为空', trigger: 'blur'},
  ],
  telephone: [
    {required: true, message: '电话不能为空', trigger: 'blur'},
  ],
  stuId: [
    {required: true, message: '工号不能为空', trigger: 'blur'},
  ],
}

  function reset(){
    Object.assign(menu,defaultValue())
  }
  onMounted(()=>{
    getPageList()
  })
  function handleQuery(){
    getPageList()
  }
  function resetQuery(){
    queryParams.menuName = null
    queryParams.status = null
    handleQuery()
  }
  const querySearch = (queryString, cb) => {
    const results = queryString
        ? restaurants.value.filter(createFilter(queryString))
        : restaurants.value
    // call callback function to return suggestions
    cb(results)
  }
  const createFilter = (queryString) => {
    return (restaurant) => {
      return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      )
    }
  }

  function getPageList(){
    loading.value = true;
    getList(queryParams).then(res=>{
        tableData.value = res.data
    }).finally(()=>{
      loading.value = false
    })
  }

  function handleAdd(){
    reset()
    dialogTitle.value = '新增菜单'
    centerDialogVisible.value = true
  }
  function handleExpandAll(){
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
      refreshTable.value = true;
    });
  }

  function handleEdit(id){
    dialogTitle.value = '修改菜单'
    getMenu(id).then(res =>{
      Object.assign(menu,res.data)
    })
    centerDialogVisible.value = true
  }
  function onCancel(){
    reset()
    centerDialogVisible.value = false
  }
  function onCloseDialog(){
    centerDialogVisible.value = false
  }
  function onOpenDialog(){
    if(menuOptions.value.length == 0){
      getMenuTreeSelect().then(res => {
        menuOptions.value = [];
        const menu = { value: 0, label: '主类目', children: [] };
        menu.children = res.data
        menuOptions.value.push(menu)
      })
    }
    if(restaurants.value.length == 0){
      getIcons().then(res => {
        restaurants.value = res.data
      })
    }
  }
  function onSubmit(){
    menuForm.value.validate(valid => {
      if (valid) {
        if (menu.menuId != null) {
          updateMenu(menu).then(res => {
            ElMessage.success(res.msg);
            onCancel();
            getPageList();
          })
        } else {
          addMenu(menu).then(res => {
            ElMessage.success(res.msg);
            onCancel();
            getPageList();
          })
        }
        menuOptions.value = []
      }
    })
  }
  function handleDelete(id){
    ElMessageBox.confirm(
        '是否确认删除？',
        '系统提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
    ).then(() => {
      deleteMenu(id).then(res => {
        if(res.code == 200){
          ElMessage.success(res.msg)
        }
      }).finally(() =>{
        getPageList()
      })
    }).catch(() =>{
      ElMessage.info("取消删除")
    })
  }
</script>

<style scoped>
.label-icon-center{
  margin: auto 2px;
}
.font-bold{
  font-weight: bold;
}
</style>
